/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Core;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import org.pircbotx.PircBotX;
import org.pircbotx.exception.IrcException;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.KickEvent;
import org.pircbotx.hooks.events.*;

/**
 *
 * @author tangd
 */
public class Autorejoin extends ListenerAdapter {
    private String[] channels;
    Timer t;
    public Autorejoin(String[] channels) {
        this.channels = channels;
        t = new Timer();
    }
    public void onKick(KickEvent event) {
        if(event.getRecipient().equals(event.getBot().getUserBot())) {
            event.getBot().joinChannel(event.getChannel().getName());
        }
    }
    public void onQuit(QuitEvent event) {
        if(event.getUser().getNick().equals(event.getBot().getNick())) {
            //If it was us
            System.err.println("We disconnected");
            TimerTask task = new ReconnectTask(event.getBot());
            t.schedule(task, 10000, 300000);
        }
    }
    public void onDisconnect(DisconnectEvent event)  {
        System.err.println("We disconnected");
        TimerTask task = new ReconnectTask(event.getBot());
        t.schedule(task, 10000, 300000);
    }
    private class ReconnectTask extends TimerTask {
        PircBotX bot;
        public ReconnectTask(PircBotX bot) {
            this.bot = bot;
        }
        boolean reconnected = false;
        public void run() {
            if(!reconnected) {
                try{
                    bot.reconnect();
                    bot.identify("jarvaa");
                    for(String s : channels) {
                        bot.joinChannel(s);
                    }
                    reconnected = true;
                }
                catch(IrcException ioEx) {
                    ioEx.printStackTrace();
                }
                catch(IOException ioEx) {
                    ioEx.printStackTrace();
                }
            }
            if(reconnected) {
                cancel();
            }
        }
    }
}
